$cat = {
	getMfgName : function(id) {
		var select = $('#mfg-list');
		return select.find('option[value="' + id + '"]').text();
	},
	loadMfg : function(args) {
		$store.get({
			url : '/admin/brand/load/mfg',
			data : null,
			success : function(d) {
				var select = $('#mfg-list');
				for ( var i = 0; i < d.length; i++) {
					var c = d[i];
					option = $('<option/>');
					option.val(c.id).text(c.name);
					select.append(option);
				}
				args.onLoad();
			},
			error : function(e) {
				alert('error loading brands');
			}
		});
	},
	load : function() {
		$store.get({
			url : '/admin/brand/load',
			data : null,
			success : function(d) {
				// refresh the table
				$('#brand-table').remove();

				var table = $('#brand-table-template').clone();
				table.attr('id', 'brand-table');
				table.css('display', 'block').appendTo('#page-root');
				for ( var i = 0; i < d.length; i++) {
					var c = d[i];
					var row = table.find('tr.brand-row:first').clone();
					row.removeClass('hide');
					table.append(row);
					row.find('td::nth-child(1)').text(c.id);
					row.find('td:nth-child(2)').text(c.name);
					row.find('td:nth-child(3)').text(c.description);
					row.find('td:nth-child(4)')
							.data('mfg-id', c.manufacturerId);
					row.find('td:nth-child(4)').text(
							$cat.getMfgName(c.manufacturerId));
				}
				table.find('tr:odd').css('background-color', '#cabcab');
				$('a[title="edit"]').click(
						function() {
							var $this = $(this).closest('tr');
							$('#brand-id').val(
									$this.find('td:nth-child(1)').text());
							$('#brand-name').val(
									$this.find('td:nth-child(2)').text());
							$('#mfg-list').val(
									$this.find('td:nth-child(4)')
											.data('mfg-id'));
							$('#brand-desc').val(
									$this.find('td:nth-child(3)').text());
						});
			},
			error : function(e) {
				alert('error loading brands');
			}
		});
	},
	save : function() {
		var form = $('#brand-form');
		$store.post({
			url : '/admin/brand/save',
			data : form.serialize(),
			success : function(d) {
				alert('done');
				$('#brand-id').val(null);
				$cat.load(false);
			},
			error : function(e) {
				alert('error');
			}
		});
	}
};
$(document).ready(function() {
	$cat.loadMfg({
		onLoad : function() {
			$cat.load();
		}
	});
	$('#save-brand-button').click(function() {
		$cat.save();
	});
	$('#reset-brand-button').click(function() {
		$('#brand-id').val(null);
	});
});